package com.xxkj.drugtraceability.net

import com.google.gson.Gson
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.coroutineScope
import java.io.IOException

data class WanResponse<out T>(val code: String, val msg: String,val status: String, val data: T) {
    var errorData = ""
}

suspend fun <T : Any> WanResponse<T>.executeResponse(successBlock: (suspend CoroutineScope.() -> Unit)? = null,
                                                     errorBlock: (suspend CoroutineScope.() -> Unit)? = null): Result<T> {
    return coroutineScope {
        if (code == "-1") {
            errorBlock?.let { it() }
            if (errorData.isEmpty()) {
                errorData = Gson().toJson(data)
            }
            Result.Error(IOException(msg), errorData)
        } else {
            successBlock?.let { it() }
            Result.Success(data, msg)
        }
    }
}

suspend fun <T : Any> WanResponse<T>.doSuccess(successBlock: (suspend CoroutineScope.(T) -> Unit)? = null): WanResponse<T> {
    return coroutineScope {
        if (code == "0") successBlock?.invoke(this, this@doSuccess.data)
        this@doSuccess
    }

}

suspend fun <T : Any> WanResponse<T>.doError(errorBlock: (suspend CoroutineScope.(String) -> Unit)? = null): WanResponse<T> {
    return coroutineScope {
        if (code == "-1") errorBlock?.invoke(this, this@doError.msg)
        this@doError
    }
}

